const TOOLS = require(`./tools.js`);
const Ci = require(`./ci.js`);

module.exports = cmd = argv => {
  if (argv[1] === undefined) {
    console.log("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    console.log("Error: Please enter the correct path");
    console.log("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    return
  }
  if ((argv[1]).constructor !== String) {
    console.log("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    console.log("Error: Please enter the correct path");
    console.log("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    return
  }


  let JSONPath = argv[1];
  let deployList = TOOLS.readJSON(JSONPath);
  let taskTime = Math.fround(new Date())
  let packageMsg = TOOLS.getPackageSize(deployList[0].project)
  let isPass = TOOLS.checkPackageSize(packageMsg.countSize, packageMsg.subPackages)
  if (!isPass.isPass) {
    console.log("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    console.log(`Error: ${isPass.msg}`)
    console.log("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    return
  }
  console.log("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
  console.log(`CountSzie: ${packageMsg.countSize} kb`);
  for (let key in packageMsg.subPackages) {
    console.log(`SubPackages-${key}: ${packageMsg.subPackages[key]} kb`);
  }
  console.log(`Index page: ${packageMsg.indexPage}`);
  console.log(`Deployment list: ${deployList.length} tasks`);
  console.log("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

  let fn = (deploy, current, e) => {
    let Info = e.toString();
    if (Info.indexOf("done: upload") === 0) {
      let date = new Date()
      console.log(`speed: [${current + 1}/${deployList.length}]`);
      console.log(`app: ${deploy.name}`);
      console.log(`status: finished`);
      console.log(`time: ${date}`);
      console.log("-------------");
      if (current + 1 === deployList.length) {
        console.log("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        console.log(`Running log of this task: "C:/mps-deploy-log"`);
        console.log('Task end!');
        console.log("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
      }
      TOOLS.Log.writeLog(taskTime, JSON.stringify({
        speed: `[${current + 1}/${deployList.length}]`,
        app: ` ${deploy.name}`,
        status: `finished`,
        time: ` ${date}`,
      }))
      if (current < deployList.length - 1) {
        Ci.deploy(deployList, ++current, fn);
      }
    } 
  };
  Ci.deploy(deployList, 0, fn);
}